# /usr/bin/python3
#-*-coding:utf-8-*-
# 运行环境： ubuntu 16.04 LTS
# tensorflow 1.13.1
# opencv 3.4.1.15
# 数据集： COCO 2017
# 查看COCO数据集中的类的样本数, 以及是否做了标定框
import cv2
import random
import matplotlib as mt
import colorsys
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import os
import time
import PIL
import skimage.io as io
import xml.etree.ElementTree as ET

from pycocotools.coco import COCO
# 这里顺序要放在最后, 不然这个界面显示的GUI不会生效
mt.use('TkAgg');
# 训练集的文本的路径
train_dataset_path = 'winder_datasets//train of winder//winder_COCO.txt';
train_label_path = 'winder_datasets//train of winder//winder_label.txt';

if not os.path.exists(train_dataset_path):
    raise  ValueError('训练样本路径的文本不存在！！！');
if not os.path.exists(train_label_path):
    raise  ValueError('训练样本的标签路径的文本不存在！！！');

# 读取标签变成字典
winder_label = {};
with open(train_label_path, 'r', encoding='utf-8') as r:
    label_txt = r.readlines();
    label_ID = [ID.split()[0] for ID in label_txt];
    print(label_ID);
    print(type(label_ID[0]));
    print(len(label_ID[0]));
    #label_name = [names.split()[1:] for names in label_txt if len(names.split()[1:]) != 0];
    label_name = [];
    for names in label_txt:
        if len(names.split()[1:]) == 0:
            continue;
        temp_name = '';
        count = 0;
        for data in names.split()[1:]:
            if count > 0:
                temp_name += ' ';
            temp_name += data;
            count += 1;
        label_name.append(temp_name);
    print('标签所有类的名字： ', label_name);
    print('标签的个数： ', len(label_name));
    for i, num in enumerate(label_ID):
        #temp_ID = int(num);
        if len(label_name[i]) == 0:
            continue;
        winder_label[num] = label_name[i];
    print(winder_label);

with open(train_dataset_path, 'r', encoding='utf-8') as r:
    datasets_text = r.readlines();
    datasets_list = [data.split() for data in datasets_text if len(data.split()[1:]) != 0]
    # ['COCO//dataset_training//train2017//train2017//000000360449.jpg', '138.45,360.99,212.43,419.67,0']
    print(datasets_list[0]);
    # <class 'list'>
    print(type(datasets_list[0]));

def draw_bbox(image, bboxes, classes=label_name, show_label=True):
    """
    bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.
    """

    num_classes = len(classes)
    image_h, image_w, _ = image.shape
    hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]
    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
    colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))

    random.seed(0)
    random.shuffle(colors)
    random.seed(None)

    for i, bbox in enumerate(bboxes):
        coor = np.array(bbox[:4], dtype=np.int32)
        fontScale = 0.5
        score = bbox[4]
        class_ind = int(bbox[5])
        bbox_color = colors[class_ind]
        bbox_thick = int(0.6 * (image_h + image_w) / 600)
        c1, c2 = (coor[0], coor[1]), (coor[2], coor[3])
        cv2.rectangle(image, c1, c2, bbox_color, bbox_thick)

        if show_label:
            bbox_mess = '%s: %.2f' % (classes[class_ind], score);
            t_size = cv2.getTextSize(bbox_mess, 0, fontScale, thickness=bbox_thick//2)[0];
            cv2.rectangle(image, c1, (c1[0] + t_size[0], c1[1] - t_size[1] - 3), bbox_color, -1);  # filled

            cv2.putText(image, bbox_mess, (c1[0], c1[1]-2), cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale, (0, 0, 0), bbox_thick//2, lineType=cv2.LINE_AA);

    return image

image_path = datasets_list[19000][0]
xmin, ymin, xmax, ymax, Class_ID = datasets_list[19000][1].split(',');
print(xmin, ymin, xmax, ymax, Class_ID);
# <class 'str'> <class 'str'>
print(type(xmin), type(Class_ID));
I = io.imread(image_path);
probability = 1;
winder_bbox = [int(float(xmin)), int(float(ymin)), int(float(xmax)), int(float(ymax)), probability, int(Class_ID)];
winder_image = draw_bbox(I, [winder_bbox]);
plt.figure(1);
plt.imshow(winder_image);
plt.axis('off');
plt.show();
